package cn.apestar.common.image;

import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.Image;
import java.awt.image.BufferedImage;

/**
 * <p>
 * Title: 检索基本类
 * </p>
 * <p>
 * Description:常用工具
 * </p>
 * <p>
 * Copyright: Copyright (c) suneasy 2010
 * </p>
 * <p>
 * Company: 138do
 * </p>
 * 
 * @author wsu
 * @version 2.1 2010/11/25 17:34:56 wangsu Exp $
 */

public class Tools {
	public Tools() {
	}

	/**
	 * 截NULL
	 * 
	 * @param str
	 * @return
	 */
	public static String RmNull(String str) { // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		return str;
	}

	/**
	 * 过滤 $%^*?+_',.等符号
	 * 
	 * @param str
	 * @return
	 */
	public static String RmFilter(String str) { // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		str = str.replace('<',' '); 
		str = str.replace('>',' '); 
		str = str.replace('"',' ');
		str = str.replace('\'',' ');
		str = str.replace('/',' ');
		str = str.replace('%',' '); 
		str = str.replace(';',' '); 
		str = str.replace('(',' '); 
		str = str.replace(')',' '); 
		str = str.replace('&',' '); 
		str = str.replace('+','_'); 

		return str;
	}
	
	/**
	 * 过滤 $%^*?+_',.等符号
	 * 
	 * @param str
	 * @return
	 */
	
	public static String RmFilter2(String str) { // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		str = str.replace('<',' '); 
		str = str.replace('>',' '); 
		str = str.replace('"',' ');
		str = str.replace('\'',' ');
		//str = str.replace('/',' ');
		str = str.replace('%',' '); 
		str = str.replace(';',' '); 
		str = str.replace('(',' '); 
		str = str.replace(')',' '); 
		str = str.replace('&',' '); 
		str = str.replace('+','_'); 

		return str;
	}

	/**
	 * 读文件到缓冲里面
	 * 
	 * @param filePath
	 * @return
	 */
	public static StringBuffer readFile(String filePath) {
		// StringBuffer bStr = new StringBuffer();
		// String LineStr = "";
		// try {
		// System.setProperty("user.language", "zh");
		// System.setProperty("file.encoding", "GBK");
		// java.io.FileReader fr = new java.io.FileReader(filePath);
		//
		// java.io.BufferedReader br = new java.io.BufferedReader(
		// fr);
		// while ( (LineStr = br.readLine()) != null) {
		// bStr.append(LineStr +
		// System.getProperty("line.separator"));
		// }
		// br.close();
		// fr.close();
		// }
		// catch (Exception e) {
		// System.out.println(e.getMessage());
		// System.out.println("不能读取正文！");
		// }
		// return bStr;
		try {
			return readFile(filePath, "GBK");
		} catch (IOException ex) {
			System.out.println(ex);
			return null;
		}
	}

	public static void writeFile(String filePath, String contStr) {
		writeFile(filePath, contStr, "GBK");
	}

	public static void writeFile(String filePath, String contStr, String encoder) {
		try {
			FileOutputStream afile = new FileOutputStream(
					filePath);
			afile.write(contStr.getBytes(encoder));
			afile.close();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("Can't Written！");
		}
	}

	public static StringBuffer readFile(String filePath, String encoder)
			throws IOException {
		try {

			InputStream fis = new FileInputStream(filePath);
			byte[] b_all = new byte[fis.available()];
			byte[] readBytes = new byte[10240];
			int readInt, start = 0;
			while ((readInt = fis.read(readBytes)) != -1) {
				System.arraycopy(readBytes, 0, b_all, start, readInt);
				start += readInt;
			}
			fis.close();
			String str = new String(b_all, encoder);
			return new StringBuffer(str);
		} catch (IOException e) {
			System.out.println("read  the file " + filePath + " err:"
					+ e.toString());
			throw e;
		}

	}

	/**
	 * 日期格式化
	 * 
	 * @param date
	 *            需要格式化日期
	 * @param pattern
	 *            需要格式话的PATTERN
	 * @return 返回格式化的效果
	 */
	public static String dateToStr(Date date, String pattern) {
		SimpleDateFormat formater = new SimpleDateFormat(
				pattern);
		return formater.format(date);
	}

	/**
	 * 日期格式化 判断日期是否超届
	 * 
	 * @param date
	 *            需要格式化日期
	 * @return 返回格式化的效果
	 */
	public static String dateFormat(String str) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format.parse(str);
			str = format.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
			str = "2010-02-19";
		}

		return str;
	}

	/**
	 * 替换字符窜，虽然1。4有功能，但为了能再1。2能用所以用此函数
	 * 
	 * @param source
	 * @param oldString
	 * @param newString
	 * @return
	 */
	public static String Replace(String source, String oldString,
			String newString) {
		StringBuffer output = new StringBuffer(); // define String Buffer
		int lengthOfSource = source.length(); // 源字符串长度
		int lengthOfOld = oldString.length(); // 老字符串长度
		int posStart = 0; // 开始搜索位置
		int pos; // 搜索到老字符串的位置
		while ((pos = source.indexOf(oldString, posStart)) >= 0) {
			output.append(source.substring(posStart, pos));

			output.append(newString);
			posStart = pos + lengthOfOld;
		}

		if (posStart < lengthOfSource) {
			output.append(source.substring(posStart));
		}

		return output.toString();
	}

	public static void mkDir(String filePath) {
		File file = new File(filePath);
		try {
			file.mkdirs();
			System.out.println("make dir ok!");
		} catch (Exception e) {
			System.out.println("mkdir error:" + e);
		}
	}

	/**
	 * 回车换行
	 * 
	 * @param Content
	 * @return
	 */
	public static String addBR(String Content) {
		String makeContent = "";
		StringTokenizer strToken = new StringTokenizer(Content, "\n");
		while (strToken.hasMoreTokens()) {
			makeContent = makeContent + strToken.nextToken() + "<br>";
		}
		makeContent = makeContent.replaceAll("  ", "　");
		return makeContent;
	}

	/**
	 * 字符集转换
	 * 
	 * @param s
	 * @return
	 */
	public static String ISO8859_1ToGBK(String s) {
		try {
			// s = new String(s.getBytes("ISO-8859-1"), "GBK");
		} catch (Exception e) {
			System.out.println("ISO8859_1ToGBK" + e);
		}
		return s;
	}

	/**
	 * 字符集转换
	 * 
	 * @param s
	 * @return
	 */
	public static String GBKToISO8859_1(String s) {
		try {
			// s = new String(s.getBytes("GBK"), "ISO-8859-1");
		} catch (Exception e) {
			System.out.println("GBKToISO8859_1" + e);
		}
		return s;
	}

	/**
	 * 替换字符缓冲中所有的标签
	 * 
	 * @param strb
	 *            缓冲
	 * @param sStr
	 *            原字符
	 * @param nString
	 *            新字符
	 * @return
	 */
	public static StringBuffer replaceAll(StringBuffer strb, String sStr,
			String nString) {
		int start = 0;
		while ((start = strb.indexOf(sStr, start)) > -1) {
			strb.replace(start, start + sStr.length(), nString);
			start = start + nString.length();
		}
		return strb;
	}

	/**
	 * 格式话法规，论文，专用
	 * 
	 * @param strb
	 *            需要格式的字符缓冲
	 * @return
	 */
	public static StringBuffer txtFormat(StringBuffer strb) {
		String LineStr = "";
		int s0 = 0;
		int s1 = 0;
		int s2 = 0;
		int s3 = 0;
		StringBuffer tmpBuffer = new StringBuffer();
		String lineSpr = System.getProperty("line.separator");
		while (strb.indexOf(lineSpr) > -1) {
			LineStr = strb.substring(0, strb.indexOf(lineSpr)); // 取一行
			strb.delete(0, strb.indexOf(lineSpr) + lineSpr.length()); // 删除这一行
			s0 = LineStr.indexOf("    "); // 四个空格
			s1 = LineStr.indexOf("      "); // 六个
			s2 = LineStr.indexOf("                                    "); // 36个
			s3 = LineStr.indexOf("<pre>");

			if (s3 == 0) {
				tmpBuffer.append(LineStr);
				while (strb.indexOf(lineSpr) > -1) {
					LineStr = strb.substring(0, strb.indexOf(lineSpr)); // 取一行
					strb.delete(0, strb.indexOf(lineSpr) + lineSpr.length()); // 删除这一行
					s3 = LineStr.indexOf("</pre>");
					tmpBuffer.append(LineStr + lineSpr);
					if (s3 == 0) {
						break;
					}
				}
			}

			if (s0 == 0) {
				if (s1 == 0) {
					if (s2 == 0) {
						tmpBuffer.append("<div align=right>" + LineStr.trim()
								+ "</div>");
					} else {
						tmpBuffer.append("<div  align=center><strong>"
								+ LineStr.trim() + "</strong></div>");
					}
				} else {
					tmpBuffer.append("　　" + LineStr.trim() + lineSpr + "<br>");
				}
			} else {
				tmpBuffer.append(LineStr + lineSpr + "<br>");
			}

			// tmpBuffer.append(LineStr);
		}
		return tmpBuffer;
	}

	/**
	 * 删除网页标签,包括<> 及里面的字符,只留中文
	 * 
	 * @param s
	 *            String
	 * @return String
	 */
	public static String rmHtml(String str) {
		if (str == null || str.equals("")) {
			str = "";
		}
		String regEx = "[=\\'^\"./%;&<>(A-Z)(a-z)]"; // 表示一个或多个a\p{Punct}

		Pattern p = Pattern.compile(regEx);

		Matcher m = p.matcher(str);

		str = m.replaceAll("");
		str = str.replaceAll(" ", "");
		return str;
	}

	// 过滤网页代码
	public static String rmHtml2(String page) {
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(page);
		page = m_html.replaceAll(""); // 过滤html标签

		return page;
	}

	public static void test(int arr[]) {
		int[] tempArr = new int[] { 1, 23, 4, 100, 222, 21 };
		// arr = new int [tempArr.length];
		for (int i = 0; i < tempArr.length; i++) {
			arr[i] = tempArr[i];
		}
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// Tools tools1 = new Tools();
		// System.out.println(Tools.dateToStr(new Date(),"yyyy-MM-dd
		// hh:MM:ss"));
		// System.out.println(Tools.strToDate(2003,12,23));
		// System.out.println(Tools.trimTxt(Tools.readFile("d:/test/chl001s232.txt"),15,
		// 20));
		// mkDir("d:/test/test/test/test/test/test/test");
		// System.out.println(xmlSpecial("<安徽大学>法律评论"));
		/*
		 * int[] arr = new int[] { 1, 4, 7, 2, 35, 3, 45, 33}; int[] arr1 = new
		 * int[] { 1, 4, 2, 33, 33}; //arr=Tools.delArr(arr,2);
		 * Arrays.sort(arr1); arr = Tools.getDiff(arr, arr1);
		 * Tools.printArr(arr); //Arrays.sort(arr); // Tools.printArr(arr);
		 */
		// System.out.println(Tools.rmHtml2(
		// "<a href='/showtxt?的' >中华人民共和国兵役法</a><br>...治县、市、市辖区的人民政府给予补助。"));
		try {
			// String str = Tools.readFile("d:/pie.xml", "utf-8").toString();
			// System.out.println(str);
			// Tools.writeFile("d:/tt.xml", str, "utf-8");
			Tools.copyFile("E:\\20110507135644562.jpg", "e:\\2.jpg");

			System.out.println(Tools.getType("118"));
		} catch (Exception ex) {
		}
	}

	/**
	 * MD5加密
	 * 
	 * @param s
	 *            String
	 * @return String
	 */

	public static String toMD5(String str) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
		return new BigInteger(md.digest()).toString(16);
	}

	/**
	 * copy 复制文件 oldPath 源文件 savePath 复制后文件地址
	 */

	public static void copyFile(String oldPath, String savePath) {

		try {
			//System.out.println(oldPath);
			//System.out.println(savePath);
			File temp = new File(oldPath);

			if (temp.isFile()) {
				FileInputStream input = new FileInputStream(temp);
				FileOutputStream output = new FileOutputStream(savePath);
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = input.read(b)) != -1) {
					output.write(b, 0, len);
				}
				output.flush();
				output.close();
				input.close();
			}

		} catch (Exception e) {
			System.out.println("copy file error"+e);
		}
	}

	/**
	 * isNumber 判断是否数字 s 不是返回0 容错处理
	 */

	public static int isNumber(String s) {
		int tempid = 0;
		try {
			tempid = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			tempid = 0;
		}
		return tempid;
	}

	/**
	 * isNumber 判断是否手机号s 不是返回0 容错处理
	 */

	public static String isMob(String s) {
		String tempid = "";
		try {
			String regex = "^1\\d{10}$";
			boolean isMob = s.matches(regex);
			if (isMob)
				tempid = s;
			else
				tempid = "";
		} catch (NumberFormatException e) {
			tempid = "";
		}
		return tempid;
	}
	
	/**
	 * getType 根据传值获取分类中文名称
	 */
	public static String getType(String value) { 
		String ctype = "";
		Hashtable table = new Hashtable();
		table.put("1","网站资讯");
		table.put("2","帮助中心");
		table.put("3","网站底部信息");
		table.put("4","网站动态");
		table.put("5","帮助中心");
		table.put("6","关于我们");
		table.put("7","用户条款");
		table.put("8","商家分类");
		table.put("9","服装饰品");
		table.put("10","餐饮美食");
		table.put("11","女装");
		table.put("12","男装");
		table.put("13","家常菜");
		table.put("14","地方菜");
		table.put("15","站内广告管理");
		table.put("16","首页广告");
		table.put("17","品牌导航首页");
		table.put("18","首页滚动焦点5张图");
		table.put("19","专卖店");
		table.put("20","内衣");
		table.put("21","鞋");
		table.put("22","箱包皮具");
		table.put("23","配饰");
		table.put("24","户外装备");
		table.put("25","专业机构");
		table.put("26","便民服务");
		table.put("27","休闲娱乐");
		table.put("28","美容健身");
		table.put("29","数码电器");
		table.put("30","婚嫁母婴");
		table.put("31","建材家居");
		table.put("32","旅游住宿");
		table.put("33","教育培训");
		table.put("34","车行服务");
		table.put("35","文体礼品");
		table.put("36","商场超市");
		table.put("37","理财担保");
		table.put("38","律师事务所");
		table.put("39","医院诊所");
		table.put("40","银行");
		table.put("41","保险");
		table.put("42","金融证券");
		table.put("43","学校");
		table.put("44","政府机构");
		table.put("45","特色小吃");
		table.put("46","火锅");
		table.put("47","烧烤");
		table.put("48","海鲜");
		table.put("49","西餐简餐");
		table.put("50","异国风味");
		table.put("51","蛋糕西饼");
		table.put("52","邮局");
		table.put("53","通信营业厅");
		table.put("54","房屋中介");
		table.put("55","医药保健");
		table.put("56","家政服务");
		table.put("57","搬家公司");
		table.put("58","物流快递");
		table.put("59","送水送气");
		table.put("60","洗衣制衣");
		table.put("61","洗浴桑拿");
		table.put("62","KTV");
		table.put("63","酒吧迪厅");
		table.put("64","影剧院");
		table.put("65","棋牌台球");
		table.put("66","网吧游艺");
		table.put("67","动漫音像");
		table.put("68","茶社咖啡厅");
		table.put("69","冷饮水吧");
		table.put("70","户外运动");
		table.put("71","电器维修");
		table.put("72","电脑维修");
		table.put("73","擦鞋开锁");
		table.put("74","宠物");
		table.put("75","粮油果蔬");
		table.put("76","数码快印");
		table.put("77","整容整形");
		table.put("78","足浴足疗");
		table.put("79","推拿按摩");
		table.put("80","美容美发");
		table.put("81","美体减肥");
		table.put("82","美甲");
		table.put("83","健身俱乐部");
		table.put("92","电器");
		table.put("93","小家电");
		table.put("94","手机通讯");
		table.put("95","数码影音");
		table.put("96","电脑");
		table.put("97","DIY");
		table.put("98","办公耗材");
		table.put("99","软件点卡");
		table.put("100","电玩产品");
		table.put("103","婚纱摄影");
		table.put("104","儿童摄影");
		table.put("105","备用");
		table.put("106","婚庆婚介");
		table.put("107","珠宝首饰");
		table.put("108","童装童鞋");
		table.put("109","母婴用品");
		table.put("110","儿童玩具");
		table.put("111","亲子早教");
		table.put("112","婴儿游泳");
		table.put("115","装修公司");
		table.put("116","厨房卫浴");
		table.put("117","瓷砖地板");
		table.put("118","灯具五金");
		table.put("119","门窗");
		table.put("120","暖通");
		table.put("121","建材");
		table.put("122","家具");
		table.put("123","家居家纺");
		table.put("132","旅行社");
		table.put("133","旅游景点");
		table.put("134","星级酒店");
		table.put("135","快捷酒店");
		table.put("136","度假村");
		table.put("137","旅店");
		table.put("138","票务代售");
		table.put("153","培训机构");
		table.put("154","家教");
		table.put("155","考试");
		table.put("156","幼儿园");
		table.put("157","驾校");
		table.put("169","展厅4S店");
		table.put("170","二手租赁");
		table.put("171","汽车用品");
		table.put("172","加油站");
		table.put("173","修车洗车");
		table.put("174","电动车");
		table.put("175","摩托车");
		table.put("176","自行车");
		table.put("185","图书文具");
		table.put("186","打印复印");
		table.put("187","设计制图");
		table.put("188","报刊杂志");
		table.put("189","琴行乐器");
		table.put("190","工艺品");
		table.put("191","收藏品");
		table.put("192","手表");
		table.put("193","土特产");
		table.put("198","购物广场");
		table.put("199","超市量贩");
		table.put("200","烟酒茶叶");
		table.put("201","连锁店");
		table.put("202","小商品");
		table.put("203","便利店");
		table.put("209","花店");
		table.put("211","隐私保护");
		table.put("212","免责声明");
		table.put("213","联系我们");
		table.put("214","网站地图");
		table.put("215","广告服务");
		table.put("216","诚聘英才");
		table.put("217","首页焦点下部3张图");
		table.put("219","首页右侧促销上文字链4个");
		table.put("220","首页右侧促销上部图1个");
		table.put("221","首页右侧促销中部图3个");
		table.put("222","首页右侧促销下部图1个 ");
		table.put("223","首页导航下部8张图");
		table.put("224","新手指南");
		table.put("225","1F左侧12个");
		table.put("226","1F中间");
		table.put("227","1F右侧文字链");
		table.put("228","1F右侧下");
		table.put("229","2F左侧");
		table.put("230","2F中间");
		table.put("231","2F右侧文字链");
		table.put("232","2F右侧下");
		table.put("233","3F左侧");
		table.put("234","3F中间");
		table.put("235","3F右侧文字链");
		table.put("236","3F右侧下");
		table.put("237","4F左侧");
		table.put("238","4F中间");
		table.put("239","4F右侧文字链");
		table.put("240","4F右侧下");
		table.put("241","5F左侧");
		table.put("242","5F中间");
		table.put("243","5F右侧文字链");
		table.put("244","5F右侧下");
		table.put("245","6F左侧");
		table.put("246","6F中间");
		table.put("247","6F右侧文字链");
		table.put("248","6F右侧下");
		table.put("249","7F左侧");
		table.put("250","7F中间");
		table.put("251","7F右侧文字链");
		table.put("252","7F右侧下");
		table.put("253","8F左侧");
		table.put("254","8F中间");
		table.put("255","8F右侧文字链");
		table.put("256","8F右侧下");
		table.put("257","地产楼盘");
		table.put("258","品牌热搜排行榜10个");
		table.put("259","品牌折扣区18个");
		table.put("260","推荐品牌24个");
		table.put("261","1F精选品牌6个");
		table.put("262","2F精选品牌6个");
		table.put("263","3F精选品牌6个");
		table.put("264","4F精选品牌6个");
		table.put("265","5F精选品牌6个");
		table.put("266","6F精选品牌6个");
		table.put("267","7F精选品牌6个");
		table.put("268","8F精选品牌6个");
		table.put("269","9F精选品牌6个");
		table.put("270","10F精选品牌6个");
		table.put("271","11F精选品牌6个");
		table.put("272","12F精选品牌6个");
		table.put("273","13F精选品牌6个");
		table.put("274","14F精选品牌6个");
		table.put("275","品牌导航分类内页");
		table.put("276","1F精选品牌6个");
		table.put("277","1F所有品牌");
		table.put("278","2F精选品牌6个");
		table.put("279","2F所有品牌");
		table.put("280","3F精选品牌6个");
		table.put("281","3F所有品牌");
		table.put("282","4F精选品牌6个");
		table.put("283","4F所有品牌");
		table.put("284","5F精选品牌6个");
		table.put("285","5F所有品牌");
		table.put("286","6F精选品牌6个");
		table.put("287","6F所有品牌");
		table.put("288","7F精选品牌6个");
		table.put("289","7F所有品牌");
		table.put("290","8F精选品牌6个");
		table.put("291","8F所有品牌");
		table.put("292","9F精选品牌6个");
		table.put("293","9F所有品牌");
		table.put("294","10F精选品牌6个");
		table.put("295","10F所有品牌");
		table.put("296","11F精选品牌6个");
		table.put("297","11F所有品牌");
		table.put("298","12F精选品牌6个");
		table.put("299","12F所有品牌");
		table.put("300","13F精选品牌6个");
		table.put("301","13F所有品牌");
		table.put("302","14F精选品牌6个");
		table.put("303","14F所有品牌");
		table.put("304","友情链接");
		if (table.containsKey(value))
		{
			ctype = (String)table.get(value);
		}
		return ctype;
	}
	
	
	public static boolean isLetter(char c) {  
        int k = 0x80;  
        return c / k == 0 ? true : false;  
    }  
  
    /** 
     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1 
     *  
     * @param s 需要得到长度的字符串 
     * @return i得到的字符串长度 
     */  
    public static int strLength(String s) {  
        if (s == null)  
            return 0;  
        char[] c = s.toCharArray();  
        int len = 0;  
        for (int i = 0; i < c.length; i++) {  
            len++;  
            if (!isLetter(c[i])) {  
                len++;  
            }  
        }  
        return len;  
    }  

}
